from collections import namedtuple

from django.shortcuts import render
from .models import *
from django.http import HttpResponse, JsonResponse
from rest_framework.decorators import api_view
from .models import *
import json


# Create your views here.


from .models import *
import json
from django.utils import timezone

# Create your views here.

def UnJson(jsonData):
    json_str = json.dumps(jsonData)
    data = json.loads(json_str, object_hook=lambda d: namedtuple('data', d.keys())(*d.values()))
    return data



def giveAccount(request):
    S = account.objects.all()
    return HttpResponse(S)


def studentAccount(request):
    # 选出学生账户
    S = account.objects.filter(role=1)
    return HttpResponse(S)

@api_view(['POST'])
# 用户登录的方法
def user_login(request):
    user_id = request.POST['account']
    password = request.POST['password']
    print(user_id)
    print(password)
    # print(data)
    try:
        user = account.objects.filter(id=user_id, password=password)
        print(user.values())
        if user:
            data = {'code': 200, 'message': 'sendsuceed', 'role': user[0].role, 'account': user[0].id, }
            response = HttpResponse(json.dumps(data))
            # response.set_cookie("token", create_token(data.account), 1800)
            response.status_code = 200
            print(response)
            return response
    except IOError:
        print("233333")
    else:
        data = {'code': 403,  'message': '用户名或密码错误'}
        response = HttpResponse(json.dumps(data))
        print('用户名或密码错误')
        return response

@api_view(['POST'])
# 用户注册的方法
def user_sign_up(request):
    # data = UnJson(request.data)
    user_id = request.POST['account']
    user_password = request.POST['password']
    user_role = int(request.POST['role'])
    user = account.objects.filter(id=user_id, password=user_password)
    if len(user) == 0:
        if user_role == 0:
            user_name = request.POST['name']
            account.objects.create(id=user_id, password=user_password, role=user_role)
            student.objects.create(id=user_id, name=user_name, balance=0)
        if user_role == 1:
            user_name = request.POST['name']
            user_card_account = request.POST['card_account']
            teacher.objects.create(id=user_id, name=user_name, card_account=user_card_account)
        data = {'code': 200, 'message': '注册成功', 'role': user_role, 'id': user_id}
        return HttpResponse(json.dumps(data))
    else:
        data = {'code': 402, 'message': '账户已被注册'}
        response = HttpResponse(json.dumps(data))
        return response

# 显示老师列表
@api_view(['POST'])
def teacher_show_list(request):
    # teacher_id = request.POST['account']
    teacher_obj = teacher.objects.values()
    teacher_introduction_list = []
    for each_teacher in teacher_obj:
        teacher_introduction_list.append({"name": each_teacher['name'], "content": each_teacher['introduction']})
    # teacher_introduction_list.append({"name": teacher_obj.name, "content": teacher_introduction.content})
    data = {'code': 200, 'message': 'sendsuceed', 'content': teacher_introduction_list}
    response = HttpResponse(json.dumps(data))
    return response

# 显示老师的博客列表
@api_view(['POST'])
def show_blog_list(request):
    # data = UnJson(request)
    account_id = request.POST['account']
    user_obj = account.objects.get(id=account_id)


    blog_obj = user_obj.blog_set.all()
    blogs = blog_obj.values()
    blog_list = []
    for each_blog in blogs:
        blog_list.append({"blog_id": each_blog['blog_id'],
                          'blog_title': each_blog['title'],
                          'create_time': each_blog['create_time'].strftime('%Y-%m-%d %H:%M:%S %p')})

    data = {'code': 200, 'message': 'sendsuceed', 'content': blog_list}
    return HttpResponse(json.dumps(data))

@api_view(['POST'])
def show_blog_content(request):

    blog_id = request.POST['blog_id']


    blogs = blog.objects.filter(blog_id=blog_id)
    blogs = blogs.values()
    blog_list = []
    for each_blog in blogs:
        blog_list.append({"blog_id": each_blog['blog_id'],
                          'blog_title': each_blog['title'],
                          'create_time': each_blog['create_time'].strftime('%Y-%m-%d %H:%M:%S %p'),
                          'content': each_blog['content']})
    data = {'code': 200, 'message': 'sendsuceed', 'content': blog_list}
    return HttpResponse(json.dumps(data))

# 写入博客
@api_view(['POST'])
def write_blog(request):
    user_id = request.POST['account']
    blog_title = request.POST['title']
    blog_content = request.POST['content']
    time = timezone.now()
    blog_id = blog.objects.order_by('blog_id').last()

    new_blog_id = str(int(blog_id.blog_id) + 1)
    obj = account.objects.get(id=user_id)
    blog.objects.create(
        id=obj,
        blog_id=new_blog_id,
        title=blog_title,
        content=blog_content,
        create_time=time.strftime("%Y-%m-%d %H:%M:%S"),
        visable=1
    )
    data = {'code': 200, 'message': 'sendsuceed', 'content': "创建成功"}
    return HttpResponse(json.dumps(data))

# 给博客点赞
@api_view(['POST'])
def blog_like(request):
    data = UnJson(request)
    print(data)
    time = timezone.now()
    blog_like.objects.create(
        id=data['id'],
        blog_id=data['blog_id'],
        create_time=time.strftime("%Y-%m-%d %H:%M:%S")
    )
    data = {'code': 200, 'message': 'sendsuceed', 'content': '收藏成功'}
    return HttpResponse(json.dumps(data))

# 给博客打赏
@ api_view(['POST'])
def blog_reward(request):
    data = UnJson(request)
    print(data)
    time = timezone.now()
    obj = blog.objects.get(blog_id=data['blog_id'])
    blog.objects.create(
        id=data['id'],
        blog_id=obj,
        reward_amount=data['reward_amount'],
        create_time=time.strftime("%Y-%m-%d %H:%M:%S")
    )
    data = {'code': 200, 'message': 'sendsuceed', 'content': '打赏成功'}
    return HttpResponse(json.dumps(data))

# 给博客评论
@ api_view(['POST'])
def blog_comment(request):
    data = UnJson(request)
    print(data)
    time = timezone.now()
    obj = blog.objects.get(blog_id=data['blog_id'])
    blog.objects.create(
        id=data['id'],
        blog_id=obj,
        content=data['content'],
        create_time=time.strftime("%Y-%m-%d %H:%M:%S")
    )
    data = {'code': 200, 'message': 'sendsuceed', 'content': '评论成功'}
    return HttpResponse(json.dumps(data))

# 创建预约
@api_view(['POST'])
def make_reservation(request):
    data = UnJson(request)
    print(data)
    student_obj = account.objects.get(id=data['student_id'])
    teacher_obj = account.objects.get(id=data['teacher_id'])
    time = timezone.now()
    reservation.objects.create(
        reservation_id=data['id'],
        create_time=time.strftime("%Y-%m-%d %H:%M:%S"),
        student_id=student_obj,
        teacher_id=teacher_obj
    )
    data = {'code': 200, 'message': 'sendsuceed', 'content': "预约成功"}
    return HttpResponse(json.dumps(data))

@api_view(['POST'])
def comment_coach(request):
    data = UnJson(request)
    print(data)
    coach.objects.create(
        reservation_id=data['id'],
        coach_status=data['coach_status'],
        score=data['score'],
        trade_status=data['trade_status']
    )
    data = {'code': 200, 'message': 'sendsuceed', 'content': "评论成功"}
    return HttpResponse(json.dumps(data))

@api_view(['POST'])
def collectbox(request):
    data = UnJson(request)
    print(data)
    obj = account.objects.get(data['id'])
    collectbox.objects.create(
        id=obj,
        collectbox_id=data['collectbox_id'],
        name=data['name'],
        category=data['category'],
        content=data['content']
    )
    data = {'code': 200, 'message': 'sendsuceed', 'content': "创建成功"}
    return HttpResponse(json.dumps(data))

@api_view(['POST'])
def show_collectbox(request):
    data = UnJson(request)
    print(data)
    obj = account.objects.get(id=data['id'])
    collectboxs = obj.collectbox.all()
    collectbox_list = []
    for each_collectbox in collectboxs:
        collectbox_list.append({'collectbox_id': each_collectbox.collectbox_id,
                                'name': each_collectbox.name,
                                'category': each_collectbox.category,
                                'content': each_collectbox.content})

    data = {'code': 200, 'message': 'sendsuceed', 'content': collectbox_list}
    return HttpResponse(json.dumps(data))

# 收藏仓库
@api_view(['POST'])
def collectbox_like(request):
    data = UnJson(request)
    print(data)
    time = timezone.now()
    obj = collectbox.objects.get(collectbox_id=data['collectbox_id'])
    collectbox_like.objects.create(
        id=data['id'],
        collectbox_id=obj,
        create_time=time.strftime("%Y-%m-%d %H:%M:%S")
    )
    data = {'code': 200, 'message': 'sendsuceed', 'content': '收藏成功'}
    return HttpResponse(json.dumps(data))

